package cetc54.zhtx.start;

import cetc54.zhtx.client.HeartBeatClient;
import cetc54.zhtx.entity.HeartBeat;
import cetc54.zhtx.server.HeartBeatServer;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

/**
 * 双机热备驱动类
 *
 * @author lipeng
 */
@Slf4j
public class HotStandbyService {

    public HotStandbyService(HeartBeat heartBeat) {
        this.heartBeat = heartBeat;
    }

    private HeartBeat heartBeat;

    private HeartBeatServer heartBeatServer;

    private HeartBeatClient heartBeatClient;


    /**
     * 启动双机热备
     */
    public void startHotStandby(ServerListenStatus serverListenStatus, ClientListenStatus clientListenStatus) {
        //是否启动
        if(!heartBeat.isStart()){
            return;
        }
        if (StringUtils.isEmpty(heartBeat.getStandbyIp())){
            throw new NullPointerException("主机或备机ip为null,请检查");
        }
        if (heartBeat.isMasterStandby()) {
            heartBeatClient = new HeartBeatClient(heartBeat,clientListenStatus);
        } else {
            //默认备机工作
            if (serverListenStatus != null) {
                serverListenStatus.standbyWork();
            }
            heartBeatServer = new HeartBeatServer(heartBeat,serverListenStatus);
        }
    }


    /**
     * 停止备机服务器
     */
    public void stopStandby() {
        heartBeatServer.stopServer();
    }

    /**
     * 停止主机
     */
    public void stopMaster() {
        heartBeatClient.stopClient();
    }

}
